package myoa

import myoa.tool.SessionTool
import org.apache.commons.logging.LogFactory

import javax.servlet.Filter
import javax.servlet.FilterConfig
import javax.servlet.ServletRequest
import javax.servlet.ServletResponse
import javax.servlet.FilterChain
import javax.servlet.http.HttpServletRequest
import javax.servlet.http.HttpSession
import javax.servlet.http.HttpServletResponse

class StaticFilter implements Filter {
    private static final log = LogFactory.getLog(this)

    @Override
    void init(FilterConfig filterConfig) {
        log.debug('StaticFilter init')
    }

    @Override
    void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain chain) {
        log.info('static resource is tried to access')

        HttpServletRequest request = (HttpServletRequest) servletRequest
        HttpServletResponse response = (HttpServletResponse) servletResponse
        HttpSession session = request.getSession(false) //若存在会话则返回该会话，否则返回NULL

        //只要登录用户，就可以访问静态资源：download、file-store
        User loginUser
        if (session != null) {
            loginUser = SessionTool.getLoginUser(session)
        }
        if (loginUser != null) {
            log.info("${loginUser.name} access static resource success")
            chain.doFilter(servletRequest, servletResponse);//放行。让其走到下个链或目标资源中
        } else {
            log.info('some body (without login) access static resource failed')
            response.sendRedirect(request.getContextPath() + "/auth/login")
        }
    }

    @Override
    void destroy() {
        log.debug('StaticFilter destroy')
    }
}
